//
//  SearchViewController.m
//  Grammar
//
//  Created by Rick on 6/25/13.
//
//

#import "SearchViewController.h"
#import "UpdateHintView.h"
#import "Knowledge.h"
#import "SearchListCell.h"
#import "ITTXibViewUtils.h"
#import "SearchResultCell.h"
#import "KnowledgeDetailViewController.h"
#import "AppDelegate.h"
#import "SyncGramarsDataRequest.h"
#import "GetTagDataRequest.h"
#import "GetKeywordDataRequest.h"
#import "GetGrammarDataRequest.h"
#import "GrammarManager.h"
#import "Grammar.h"
#import "Tag.h"
#import "TagManager.h"
#import "KeywordManager.h"
#import "Keyword.h"
#import "SyncKeywordDataRequest.h"
#import "WebViewController.h"

#define GET_KEYWORD_DATA_REQUEST    @"GET_KEYWORD_DATA_REQUEST"
#define GET_GRAMMAR_DATA_REQUEST    @"GET_GRAMMAR_DATA_REQUEST"
#define GET_TAG_DATA_REQUEST        @"GET_TAG_DATA_REQUEST"
#define SYNC_GRAMMAR_DATA_REQUEST   @"SYNC_GRAMMAR_DATA_REQUEST"

@interface SearchViewController ()<UITextFieldDelegate,UIGestureRecognizerDelegate,UITableViewDataSource,UITableViewDelegate>
{
    UpdateHintView *_updateView;
    NSMutableArray *_listArray;
    NSMutableArray *_listGrammarArray;
    SearchTableViewStyle _tableViewType;
    BOOL _isFromTap;
}

@property (retain, nonatomic) IBOutlet UITextField *searchTextField;
@property (retain, nonatomic) IBOutlet UIView *searchHintView;
@property (retain, nonatomic) IBOutlet UIButton *searchButton;
@property (retain, nonatomic) IBOutlet UIView *contentView;
@property (retain, nonatomic) IBOutlet UILabel *searchHintLabel;
@property (retain, nonatomic) IBOutlet UITableView *searchListTableView;
@property (retain, nonatomic) IBOutlet UIView *rulevView;

@end

@implementation SearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideKeyBoard)];
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    _tableViewType = SearchTableViewStyleList;
    _listArray = [[NSMutableArray alloc] init];
    _listGrammarArray = [[NSMutableArray alloc] init];
    
    _searchListTableView.hidden = YES;
    //hide search clear button
    _searchButton.hidden = YES;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChange) name:UITextFieldTextDidChangeNotification object:nil];
    _rulevView.bottom = [UIScreen mainScreen].bounds.size.height - 150;
    [self addUpdateHintView];
    
    if ([[KeywordManager sharedManager].keywords count] ==0) {
        [self getkeywordDataRequest];
    }
    
    NSString *wholeString = (NSString*)[[DataCacheManager sharedManager] getCachedObjectByKey:WHOLE_VERSION];
    
    if (!wholeString) {
        [[DataCacheManager sharedManager] addObject:@"1" forKey:WHOLE_VERSION];
        _updateView.updateType = UpdateViewTypeNeedUpdate;
    }else {
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:wholeString forKey:@"wholeVersion"];
        [GetGrammarDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:GET_GRAMMAR_DATA_REQUEST onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
            if ([wholeString intValue] < [[request.resultDic objectForKey:@"wholeVersion"] intValue]) {
                DATA_ENV.isNeedUpdateRequest = YES;
                _updateView.updateType = UpdateViewTypeNeedUpdate;
            }else {
                DATA_ENV.isNeedUpdateRequest = NO;
                _updateView.updateType = UpdateViewTypeNewest;
            }
        } onRequestCanceled:^(ITTBaseDataRequest *request) {
            _updateView.updateType = UpdateViewTypeFailed;
        } onRequestFailed:^(ITTBaseDataRequest *request) {
            _updateView.updateType = UpdateViewTypeFailed;
        }];
        
    }
    
    
}

- (void)getGrammarDataRequest
{
    [GetGrammarDataRequest requestWithParameters:nil withIndicatorView:nil withCancelSubject:GET_GRAMMAR_DATA_REQUEST onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        for (NSDictionary *grammarDic  in [request.resultDic objectForKey:@"grammars"]) {
            
            Grammar *aGrammar = [[Grammar alloc] initWithDataDic:grammarDic];
            ITTDINFO(@" aGrammar %@",aGrammar);
            [GrammarManager sharedManager].grammarType = @"normal";
            [[GrammarManager sharedManager] addGrammar:aGrammar];
            [aGrammar release];
        }
        [self getTagsDataRequest];
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        
    }];
}

- (void)getkeywordDataRequest
{
    [GetKeywordDataRequest requestWithParameters:nil withIndicatorView:nil withCancelSubject:GET_KEYWORD_DATA_REQUEST onRequestStart:nil onRequestFinished:^(ITTBaseDataRequest *request) {
        [self getGrammarDataRequest];
    } onRequestCanceled:^(ITTBaseDataRequest *request) {
        
    } onRequestFailed:^(ITTBaseDataRequest *request) {
        
    }];
}
- (void)getTagsDataRequest
{
    //request
    
    [GetTagDataRequest requestWithParameters:nil withIndicatorView:nil withCancelSubject:GET_TAG_DATA_REQUEST onRequestStart:nil
        onRequestFinished:^(ITTBaseDataRequest *request) {
        
        } onRequestCanceled:^(ITTBaseDataRequest *request) {
        
        } onRequestFailed:^(ITTBaseDataRequest *request) {
                                       
        }];
}

- (void)syncGrammarsDataRequest
{
    //request
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"14" forKey:@"wholeVersion"];
    
    [SyncGramarsDataRequest requestWithParameters:parameters withIndicatorView:nil withCancelSubject:SYNC_GRAMMAR_DATA_REQUEST
                                   onRequestStart:^(ITTBaseDataRequest *request) {
                                       ITTDINFO(@"1234444");
                                   } onRequestFinished:^(ITTBaseDataRequest *request) {
                                       
                                   } onRequestCanceled:^(ITTBaseDataRequest *request) {
                                       
                                   } onRequestFailed:^(ITTBaseDataRequest *request) {
                                       
                                   }];
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    //Touch gestures below top bar should not make the page turn.
    //EDITED Check for only Tap here instead.
    if ([touch.view isKindOfClass:[UIButton class]] || [touch.view isKindOfClass:[UITextField class]] || [[touch.view superview] isKindOfClass:[UITableViewCell class]]) {
        return NO;
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return YES;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[AppDelegate shareAppdelegate].homeTabbarController showTabBarAnimated:YES];
//    if (DATA_ENV.isNeedUpdateRequest) {
//        [self addUpdateHintView];
//    }
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] postNotificationName:GET_KEYWORD_DATA_REQUEST object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:GET_GRAMMAR_DATA_REQUEST object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:GET_TAG_DATA_REQUEST object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:SYNC_GRAMMAR_DATA_REQUEST object:nil];
    [_updateView stopRequest];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
    [_listGrammarArray release];
    [_searchTextField release];
    [_searchHintView release];
    [_searchButton release];
    [_contentView release];
    [_searchHintLabel release];
    [_searchListTableView release];
    [_rulevView release];
    [super dealloc];
}

- (void)viewDidUnload
{
    [self setSearchTextField:nil];
    [self setSearchHintView:nil];
    [self setSearchButton:nil];
    [self setContentView:nil];
    [self setSearchHintLabel:nil];
    [self setSearchListTableView:nil];
    [self setRulevView:nil];
    [super viewDidUnload];
}

- (void)addUpdateHintView
{
    _updateView = [UpdateHintView loadFromXib];
    if (isReachability) {
        _updateView.updateType = UpdateViewTypeCheckUpdate;
    }else {
        _updateView.updateType = UpdateViewTypeNotNetwork;
    }
    
    [self.view addSubview:_updateView];
    _updateView.bottom = SCREEN_HEIGHT - 70;
}

- (IBAction)tapHelpButton:(id)sender {
    WebViewController *viewController = [[WebViewController alloc] initWithNibName:@"WebViewController" bundle:nil];
    viewController.type = WebviewContentTypeHelpUse;
    [self.navigationController pushViewController:viewController animated:YES];
    [viewController release];
}

#pragma mark - UITextFieldDelegate

- (void)textFieldChange
{
    if (![_searchTextField.text isEqualToString:@""]) {
        _searchButton.hidden = NO;
        [self doSearchWithString:_searchTextField.text];
    }else {
        _searchButton.hidden = YES;
        [_listArray removeAllObjects];
        [_searchListTableView reloadData];
    }
    
}

- (void)doSearchWithString:(NSString*)searchText
{
    NSArray *keywordArray = [NSArray arrayWithArray:[KeywordManager sharedManager].keywords];
    [_listArray removeAllObjects];
    for (Keyword *keyword in keywordArray) {
        NSRange range = [keyword.name rangeOfString:[searchText lowercaseString]];
        if (range.location != NSNotFound) {
            [self addSearchString:keyword.name];
        }
    }
    
    if ([_listArray count] > 0) {
        [self showTableView];
    }else {
        [self hideTableView];
    }
    
    if (!_isFromTap) {
        _isFromTap = NO;
        _tableViewType = SearchTableViewStyleList;
        _searchHintLabel.text = @"请输入语法点:";
    }
    
    [_searchListTableView reloadData];
}

- (void)addSearchString:(NSString*)searchString
{
    if ([searchString isEqualToString:@""]) {
        return;
    }
    for (NSString *searchText in _listArray) {
        if ([searchString isEqualToString:searchText]) {
            return;
        }
    }
    [_listArray addObject:searchString];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    //
    if ([_listArray count] > 0) {
        // show the table view and hide the hint view
        [self showTableView];
        _tableViewType = SearchTableViewStyleResult;
        [self showGrammarTableView:0];
        
    }else  {
        // hide table view and show the hint view
        [self hideTableView];
        [_searchListTableView reloadData];
    }
    
    
    
    return YES;
}

- (void)showTableView
{
    // do something show the tableview
    _searchHintView.hidden = YES;
    _searchListTableView.hidden = NO;
}

- (void)hideTableView
{
    _searchHintView.hidden = NO;
    _searchListTableView.hidden = YES;
}

- (IBAction)tapClearSearchButton:(id)sender {
    if (_tableViewType == SearchTableViewStyleResult) {
        [UIView animateWithDuration:0.5f animations:^{
            _searchListTableView.left = 320;
        }completion:^(BOOL finished) {
            _searchTextField.text = @"";
            [_listGrammarArray removeAllObjects];
            [_listArray removeAllObjects];
            [_searchListTableView reloadData];
            
            [self hideTableView];
            _tableViewType = SearchTableViewStyleList;
            _searchHintLabel.text = @"请输入语法点:";
            _searchListTableView.left = 0;
        }];
    }else {
        _searchTextField.text = @"";
        [_listGrammarArray removeAllObjects];
        [_listArray removeAllObjects];
        [_searchListTableView reloadData];
        
        [self hideTableView];
        _tableViewType = SearchTableViewStyleList;
        _searchHintLabel.text = @"请输入语法点:";
    }
    
    
}
#pragma mark - Hide Keyboard
- (void)hideKeyBoard
{
    _isFromTap = YES;
    [_searchTextField resignFirstResponder];
    
}


#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_tableViewType == SearchTableViewStyleList) {
        if ([_listArray count] > 0) {
            [self showTableView];
        }else {
            [self hideTableView];
        }
        return [_listArray count];
    }else {
        if ([_listGrammarArray count] > 0) {
            [self showTableView];
        }else {
            [self hideTableView];
        }
        return [_listGrammarArray count];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (_tableViewType) {
        case SearchTableViewStyleList:
            return 35;
            break;
        case SearchTableViewStyleResult:
            return 81;
            break;
        default:
            break;
    }
    return 0;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (_tableViewType) {
        case SearchTableViewStyleList:
        {
            NSString *identifer = @"SearchListCell";
            SearchListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
            if (!cell) {
                cell = [ITTXibViewUtils loadViewFromXibNamed:identifer];
            }
            cell.index = indexPath.row;
            [cell setCellTextWithSearchString:[_listArray objectAtIndex:indexPath.row]];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        case SearchTableViewStyleResult:
        {
            _searchHintLabel.text = @"你搜索的是:";
            
            NSString *identifer = @"SearchResultCell";
            SearchResultCell *cell = [tableView dequeueReusableCellWithIdentifier:identifer];
            if (!cell) {
                cell = [ITTXibViewUtils loadViewFromXibNamed:identifer];
            }
            cell.moreOptionButton.hidden = YES;
            [cell setCellWithGrammar:[_listGrammarArray objectAtIndex:indexPath.row]];
            if (indexPath.row %2) {
                cell.contentView.backgroundColor = [UIColor colorWithRed:234/255.0 green:228/255.0 blue:218/255.0 alpha:1.0];
            }else {
                cell.contentView.backgroundColor = [UIColor colorWithRed:217/255.0 green:208/255.0 blue:195/255.0 alpha:1.0];
            }
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }
            break;
        default:
            break;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_tableViewType == SearchTableViewStyleList) {
        
        [self showGrammarTableView:indexPath.row];
        _searchListTableView.left = 320;
        [UIView animateWithDuration:0.5f animations:^{
            _searchListTableView.left = 0;
        }];
        
    }else {
        KnowledgeDetailViewController *viewController = [[KnowledgeDetailViewController alloc] initWithNibName:@"KnowledgeDetailViewController" bundle:nil];
        viewController.currentGrammar = [_listGrammarArray objectAtIndex:indexPath.row];
        [self.navigationController pushViewController:viewController animated:YES];
        [viewController release];
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    
}

- (void)addGrammarListObject:(Grammar*)grammar
{
    for (Grammar *aGrammar in _listGrammarArray) {
        if ([aGrammar.grammarId isEqualToString:grammar.grammarId]) {
            return;
        }
    }
    [_listGrammarArray insertObject:grammar atIndex:0];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [_searchTextField resignFirstResponder];
}
- (void)showGrammarTableView:(NSInteger)index
{
    [GrammarManager sharedManager].grammarType = @"normal";
    NSArray *grammarArray = [NSArray arrayWithArray:[GrammarManager sharedManager].grammars];
    for (Grammar *grammar in grammarArray) {
        if ([grammar.title isEqualToString:[_listArray objectAtIndex:index]]) {
            [self addGrammarListObject:grammar];
        }
        
        for (NSDictionary *keyDic in grammar.keyWords) {
            Keyword *keyword = [[Keyword alloc] initWithDataDic:keyDic];
            if ([[keyword.name lowercaseString] hasPrefix:[[_listArray objectAtIndex:index] lowercaseString]]) {
                [self addGrammarListObject:grammar];
            }
            [keyword release];
        }
    }
    
    
    //SearchListCell *cell = (SearchListCell*)[self tableView:_searchListTableView cellForRowAtIndexPath:[NSIndexPath indexPathForItem:index inSection:0]];
    SearchListCell *cell = (SearchListCell*)[self tableView:_searchListTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0]];
    _searchTextField.text = cell.titleLabel.text;
    if (_searchTextField.text.length > 5) {
        if (![[_searchTextField.text substringFromIndex:_searchTextField.text.length - 4] isEqualToString:@"条结果)"]) {
            _searchTextField.text = [NSString stringWithFormat:@"%@ (%d条结果)",_searchTextField.text,[_listGrammarArray count]];
        }
    } else {
        _searchTextField.text = [NSString stringWithFormat:@"%@ (%d条结果)",_searchTextField.text,[_listGrammarArray count]];
    }
    _tableViewType = SearchTableViewStyleResult;
    [_searchListTableView reloadData];
}
@end
